/**
 * Created by zhouli on 18/11/28
 * 选择账套，选择成本中心
 * 账套与成本中心级联
 * todo 做好支持单选与多选
 */
import React from 'react';
import {connect} from 'react-redux';
import {Modal, Input, Tag, Icon, Tree, Select, Button, message} from 'antd';
import {deepCopy, messages} from 'share/common';
import SACCService from 'components/template/select-all-cost-center-item/select-all-cost-center-item.service.js'
import 'styles/components/template/select-all-cost-center-item/select-all-cost-center.scss';

const Option = Select.Option;
let options = [];
const {TreeNode} = Tree;

class CostCenterSelector extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      options,//账套与成本中心
      visible: false,
      loading: false,
      selectedData: [],  //已经选择的数据项

      expandedKeysRole: [],
      autoExpandParentRole: true,
      selectedKeysRole: [],
    };
  }

  initData = (originSelectedData) => {
    let originD = deepCopy(originSelectedData);
    let selectedKeysRole = originD.map(item => {
      return item.id;
    })
    this.setState({
      selectedKeysRole,
      selectedData: originD
    })
  }

  componentDidMount() {
    this.initData(this.props.originSelectedData);
    this.getTenantAllSobCostCenter();
  }

  componentWillReceiveProps(nextProps) {
    this.initData(nextProps.originSelectedData);
  }

  //获取全部账套，用第一个账套，获取下面的全部成本中心
  getTenantAllSobCostCenter = () => {
    this.setState({
      loading: true,
    })
    SACCService.getTenantAllSobCostCenter()
      .then(res => {
        let _options = SACCService.delOptions(res.data);
        this.setState({
          loading: false,
          options: _options ? _options : []
        })
      })
  }

  // 多列选择---end
  //显示模板
  showModel = () => {
    this.initData(this.props.originSelectedData);
    this.setState({
      visible: true,
    })
  }
  //点取消
  handleCancel = () => {
    let originD = deepCopy(this.props.originSelectedData);
    this.setState({
      selectedData: originD,
      visible: false
    })
    this.props.onCancel && this.props.onCancel(this.props.originSelectedData);
  }
  //点击确定
  handleOk = () => {
    this.setState({
      visible: false
    })
    let {selectedData} = this.state;
    this.props.onConfirm && this.props.onConfirm(selectedData);
  }
  onMouseLeaveDepTag = (e) => {
    e.stopPropagation();
  };
  onMouseEnterDepTag = (e) => {
    e.stopPropagation();
  };
  //清除已经选择的成本中心
  onCloseDepTag = (e) => {
    e.stopPropagation();
    this.setState({
      selectedData: [],
    }, () => {
      this.props.onClear && this.props.onClear(this.state.selectedData);
    })
  };
  //渲染值
  renderVauleText = () => {
    let selectedData = deepCopy(this.state.selectedData);
    if (selectedData.length > 0 && selectedData[0].name) {
      return selectedData.map((item, index) => {
        return <Tag key={index}>{item.name}</Tag>;
      })
    } else {
      return messages('data-center.key27')/*请选择*/;
    }
  }
  //渲染值后面的关闭icon class
  renderVauleClass = () => {
    let class_name1 = "f-right select-dep-close-wrap";
    let class_name2 = "f-right select-dep-close-wrap select-dep-close-wrap-show";
    if (this.state.selectedData.length > 0) {
      return class_name2;
    } else {
      return class_name1;
    }
  }
  //渲染功能菜单树（当前角色）
  renderTreeNodes = (data) => {
    return data.map((item, index) => {
      if (item.children) {
        return (
          <TreeNode title={<div className='tree-node-title'>
            <span>{item.label}</span>
          </div>}
                    key={item.value}
                    dataRef={item}>
            {this.renderTreeNodes(item.children)}
          </TreeNode>
        );
      }
      return <TreeNode title={<div className='tree-node-title'>
        <span>{item.label}</span>
      </div>}
                       key={item.id}
                       dataRef={item}
      />;
    });
  };
  //展开当前角色
  onExpandRole = (expandedKeys) => {
    this.setState({
      expandedKeysRole: expandedKeys,
      autoExpandParentRole: false,
    });
  }
  //选择功能菜单执行回调
  onSelectRole = (selectedKeys, info) => {
    let cNode = info.node.props.dataRef;
    let selectedData = this.state.selectedData;
    let selectedKeysRole = this.state.selectedKeysRole;
    if (cNode.costCenterOID) {
      if (this.props.isSingle) {
        selectedKeysRole = selectedKeys;
        if(selectedKeys.length===0){
          selectedData = [];
        }else {
          selectedData = [cNode];
        }
      } else {
        let ca = deepCopy(selectedData);
        ca.push(cNode);
        selectedKeysRole = selectedKeys;
        selectedData = [];
        selectedKeys.map(item => {
          selectedData.push(getTById(item, ca));
        })
      }
      this.setState({
        selectedKeysRole,
        selectedData
      });
    } else {
      message.warning(messages('components.key806')/*选择账套无效，请选择成本中心*/);
    }

    function getTById(id, arr) {
      let t = null;
      arr.map(item => {
        if (id === item.id) {
          t = item;
        }
      })
      return t;
    }
  }

  render() {
    const {disabled,needCloseIcon,isSingle} = this.props;
    const {visible,expandedKeysRole,autoExpandParentRole,selectedKeysRole,options} = this.state;
    return (
      <div className="select-all-cost-center">
        <div className="input-wrap" onClick={!disabled && this.showModel}>
          <div className='input'>
            {this.renderVauleText()}
          </div>
          {!disabled &&
          needCloseIcon && <div className={this.renderVauleClass()}
                                           onMouseLeave={this.onMouseLeaveDepTag}
                                           onMouseEnter={this.onMouseEnterDepTag}
                                           onClick={this.onCloseDepTag}>
            <Icon type="close-circle" className="closeCircle"/>
          </div>}
          <div className='clear'/>
        </div>
        <Modal
          width={400}
          className="select-all-cost-center-modal"
          title={messages('components.key807')/*请选择成本中心*/}
          closable={false}
          visible={visible}
          footer={[
            <Button key="back"
                    onClick={this.handleCancel}>
              {messages('common.cancel')}
            </Button>,
            <Button key="submit"
                    type="primary"
                    onClick={this.handleOk}>
              {messages('common.ok')}
            </Button>,
          ]}
        >
          <Tree
            multiple={!isSingle}
            onExpand={this.onExpandRole}
            expandedKeys={expandedKeysRole}
            autoExpandParent={autoExpandParentRole}
            onSelect={this.onSelectRole}
            selectedKeys={selectedKeysRole}
          >
            {this.renderTreeNodes(options)}
          </Tree>
          <div className='clear'/>
        </Modal>

      </div>
    );
  }
}

CostCenterSelector.propTypes = {
  needCloseIcon: React.PropTypes.bool,//不要清除按钮
  isSingle: React.PropTypes.bool,//是不是单选
  disabled: React.PropTypes.bool,
  onConfirm: React.PropTypes.func,// 点击确认之后的回调：返回结果
  onCancel: React.PropTypes.func,//点击取消的时候
  onClear: React.PropTypes.func,//点击清除所有已经选择了的
  originSelectedData: React.PropTypes.any,//被选择了的数据
};
//这个数据用户测试组件
let testSelectedData = [
  {
    "id": "254480",
    "name": "121",
  }
]
CostCenterSelector.defaultProps = {
  needCloseIcon: true,
  isSingle: false,
  disabled: false,
  originSelectedData: []//testSelectedData
};

function mapStateToProps(state) {
  return {
    tenantMode: state.main.tenantMode,
  }
}

export default connect(mapStateToProps)(CostCenterSelector);



